package com.doujiao.auth.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.doujiao.auth.mapper.AdminGroupMapper;
import com.doujiao.auth.service.AdminGroupService;
import com.doujiao.core.auth.dto.AdminGroupQueryDTO;
import com.doujiao.core.auth.entity.AdminGroup;
import com.doujiao.core.auth.vo.AdminGroupPageVO;
import com.doujiao.core.exceptions.BusinessException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 管理员组服务实现类
 *
 * @author wuyunbin
 * @since 2025-05-24
 */
@Service
public class AdminGroupServiceImpl extends ServiceImpl<AdminGroupMapper, AdminGroup> implements AdminGroupService {

    @Override
    public AdminGroupPageVO page(AdminGroupQueryDTO queryDTO) {
        // 构建查询条件
        LambdaQueryWrapper<AdminGroup> wrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotBlank(queryDTO.getName())) {
            wrapper.like(AdminGroup::getName, queryDTO.getName());
        }
        if (queryDTO.getStatus() != null) {
            wrapper.eq(AdminGroup::getStatus, queryDTO.getStatus());
        }
        wrapper.orderByDesc(AdminGroup::getCreateTime);

        // 执行分页查询
        Page<AdminGroup> page = new Page<>(queryDTO.getCurrent(), queryDTO.getSize());
        page = this.page(page, wrapper);

        // 封装返回结果
        AdminGroupPageVO pageVO = new AdminGroupPageVO();
        pageVO.setTotal(page.getTotal());
        pageVO.setCurrent(page.getCurrent());
        pageVO.setSize(page.getSize());
        pageVO.setRecords(page.getRecords());

        return pageVO;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AdminGroup create(AdminGroup adminGroup) {
        // 检查组名是否已存在
        if (isNameExists(adminGroup.getName(), null)) {
            throw new BusinessException("管理员组名称已存在");
        }

        // 保存管理员组
        this.save(adminGroup);
        return adminGroup;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AdminGroup update(AdminGroup adminGroup) {
        // 检查管理员组是否存在
        AdminGroup existingGroup = this.getById(adminGroup.getId());
        if (existingGroup == null) {
            throw new BusinessException("管理员组不存在");
        }

        // 检查组名是否已存在（排除自身）
        if (isNameExists(adminGroup.getName(), adminGroup.getId())) {
            throw new BusinessException("管理员组名称已存在");
        }

        // 更新管理员组
        this.updateById(adminGroup);
        return adminGroup;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean delete(Long id) {
        // 检查管理员组是否存在
        AdminGroup existingGroup = this.getById(id);
        if (existingGroup == null) {
            throw new BusinessException("管理员组不存在");
        }

        // TODO: 检查是否有管理员关联到此组，如果有则不能删除
        // 这部分逻辑需要在实现管理员-组关联功能时添加

        return this.removeById(id);
    }

    /**
     * 检查组名是否已存在
     *
     * @param name 组名
     * @param excludeId 排除的ID（用于更新时排除自身）
     * @return 是否存在
     */
    private boolean isNameExists(String name, Long excludeId) {
        LambdaQueryWrapper<AdminGroup> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AdminGroup::getName, name);
        if (excludeId != null) {
            wrapper.ne(AdminGroup::getId, excludeId);
        }
        return this.count(wrapper) > 0;
    }
}